package com.nkym.wypan.exception;/*
 * @ClassName ExceptionHandler
 * @Desc TODO
 * @Author 19637
 * @Date 2023/6/5 14:45
 * @Version 1.0
 */

import com.nkym.wypan.response.BaseResponse;
import org.apache.catalina.connector.ClientAbortException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public BaseResponse systemError(Exception e, HttpServletResponse response) {
        log.error("{}", e);
        return BaseResponse.fail();
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public BaseResponse systemError(HttpRequestMethodNotSupportedException e, HttpServletResponse response) {

        log.error("{}", e);
        String method = e.getMethod();
        return BaseResponse.failPutMessage("请求方法不支持 :" + method);
    }

    @ExceptionHandler(ClientAbortException.class)
    public void systemError(ClientAbortException e) {
        log.info("远程连接关闭{}", e.getMessage());
    }


    @ExceptionHandler(BindException.class)
    public BaseResponse paramError(BindException e, HttpServletResponse response) {
        ObjectError objectError = e.getBindingResult().getAllErrors().stream().findFirst().get();
        String message = objectError.getDefaultMessage();
        log.error("{}", e);
        return BaseResponse.failPutMessage(message);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse paramError(MethodArgumentNotValidException e, HttpServletResponse response) {
        ObjectError objectError = e.getBindingResult().getAllErrors().stream().findFirst().get();
        String message = objectError.getDefaultMessage();
        log.error("{}", e);
        return BaseResponse.failPutMessage(message);
    }

    @ExceptionHandler(BusinessException.class)
    public BaseResponse BusinessException(BusinessException e, HttpServletResponse response) {
        log.error("{}", e);
        String message = e.getMessage();
        return BaseResponse.fail(e.getCode(), message);
    }
}
